<?php namespace Home\Model;
use \Hdphp\Model\Model;
use \Home\Model\Order;
class User extends Model{
//  指定表名
    protected $table = "user";
//  错误提示    
    protected $validate = array(
    	array("password",'required','新密码不能为空',3,3),
        array("password",'minLen:6','新密码不能少于6位数',3,3),
        array("confirm",'required','确认密码不能为空',3,3),
		array('confirm','_confirm','两次输入的密码不一致，请重新输入',3,3),
		array("oldpassword",'_oldpassword','原密码不正确',3,3)
    );

	
	/**
	 * confirm:判断两次密码是否一致
	 */
	public function _confirm(){
	    $password = Q("post.password");
		$confirm = Q("post.confirm");
		if($password != $confirm) return FALSE;
		return TRUE;
	}
	/**
	 * 原密码
	 */
	public function _oldpassword(){
		$uid = $_SESSION['user']['uid'];
		$data = $this->where("uid={$uid}")->find();
		$oldPassword = Q('post.oldPassword',0,'md5');
		$password = Q("post.password",0,'md5');
		if($oldPassword = $data['password']){
//			修改密码
			$this->where("uid={$uid}")->update(['password'=>$password]);
//			清除session
			View::success("修改成功",U('Login/index'));
			session_unset();
			session_destroy();
			exit;
		}
		
	}
	
//  修改
    public function store(){
        if(!$this->create()) return FALSE;
        $this->save();
        return TRUE;
    }
	
	/**
	 * 购买物品修改金钱
	 */
	public function pay(){
		$uid = $_SESSION['user']['uid'];
		$userData = $this->where("uid={$uid}")->find();
		$password = Q("post.password",'','md5');
		if($userData['password'] != $password){
			View::error('密码错误');
		}
		$orderId = Q("get.orderId");
		$orderModel = new Order();
		$orderData = $orderModel->where("number='{$orderId}'")->find();
		if($userData['password'] == $password){
			if($userData['money'] >= $orderData['total']){
			  	$price = $userData['money'] - $orderData['total'];
				$this->where("uid={$uid}")->update(['money'=>$price]);
				$orderModel->where("number='{$orderId}'")->update(['status'=>1]);
				View::success("支付成功",U('Order/index'));
			}else{
				View::error('余额不足');
			}
		}else{
			View::error('输入密码有误');
		}
	}
	
}